package com.heima;

import com.heima.entity.Monster;
import com.heima.mapper.MonsterMapper;
import com.heima.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

public class MonsterMapperTest {
    //这个是 Sql 会话,通过它可以发出 sql 语句
    private SqlSession sqlSession;
    private MonsterMapper monsterMapper;

    @Before
    public void init() throws Exception {
//通过 SqlSessionFactory 对象获取一个 SqlSession 会话
        sqlSession = MyBatisUtils.getSqlSession();
//获取 MonsterMapper 接口对象, 该对象实现了 MonsterMapper
        monsterMapper = sqlSession.getMapper(MonsterMapper.class);
        System.out.println(monsterMapper.getClass());
    }

    @Test
    public void addMonster() {
        for (int i = 0; i < 2; i++) {
            Monster monster = new Monster();
            monster.setAge(100 + i); monster.setBirthday(new Date());
            monster.setEmail("tn@sohu.com");
            monster.setGender(1); monster.setName("松鼠精" + i);
            monster.setSalary(1111 + i * 10);
            monsterMapper.addMonster(monster);
            System.out.println("刚刚添加的对象的 id=" + monster.getId());

        }
//增删改，需要提交事务
        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
        System.out.println("保存成功!");
    }
}